<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script>
export default {
  name: 'EchartsChart',
}
</script>

<script setup>
import { onMounted, ref, watch } from 'vue';
import echarts from '@/plugins/echarts'
import merge from 'lodash/merge'

const props = defineProps(['option'])


const chartRef = ref()

const commonOption = {
  xAxis: {
    // data: [],
    axisLine: {
      lineStyle: {
        color: 'rgba(255,255,255,.5)',
        opacity: 0.5
      }
    },
    axisLabel: {
      fontSize: 8,
      color: 'rgba(255,255,255,.4)'
    },
    axisTick: {
      show: false
    }
  },
  yAxis: {
    splitLine: {
      show: false
    },
    axisLine: {
      show: true, // 显示y轴
      lineStyle: {
        color: 'rgba(255,255,255,.5)',
      }
    },
    axisLabel: {
      color: 'rgba(255,255,255,.4)',
      fontSize: 8
    }
  },
  // series: [
  //   {
  //     name: '程序员数量',
  //     type: 'bar',
  //     data: [],
  //     barWidth: '40%'
  //   }
  // ],

  title: {
    // text: '各行业程序员数量',
    left: 'center',
    textStyle: {
      fontSize: 12,
      color: 'white'
    }
  },
  // 位置
  grid: {
    left: 10,
    top: 40,
    right: 10,
    bottom: 10,
    containLabel: true
  },

  // 提示框
  tooltip: {
    trigger: 'axis',
    axisPointer: { 
      type: 'shadow' // 柱的阴影
    },
    backgroundColor: 'rgba(0, 0, 0, .5)',
    textStyle: {
      color: 'white'
    },
    borderWidth: 0
  },
  // 图例
  legend: {
    top: 10,
    right: 5,
    textStyle: {
      fontSize: 8,
      color: "#fff",
    },
    itemWidth: 15,
    itemHeight: 8,
  },
}

// 挂载时初始化渲染图表
onMounted(() => {
  // 渲染图表
  renderChart()
})

let chart
// 渲染图表
function renderChart() {
  if (!chart) { // 没有才初始化产一个新的
    // 初始化产生一个图表对象
    chart = echarts.init(chartRef.value)
  }
  
  // 合并option
  const option = merge(commonOption, props.option)
  // 设置option
  chart.setOption(option)
}

// 当option中data数据发生改变时重新渲染图表
watch(props.option, renderChart, {deep: true})

</script>

<style scoped lang="scss">
.chart-container {
    width: 100%;
    height: 100%;
  }
</style>
